﻿using AngleSharp.Dom;
using AngleSharp.Dom.Html;
using AngleSharp.Parser.Html;
using DonetSpider.http;
using DonetSpider.Log;
using Newtonsoft.Json;
using System;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Linq;
using System.Collections.Generic;
using DonetSpider.Db;
using System.Reflection;

namespace DonetSpider
{
    public class SimpleSpider : HasLog
    {
        string tempData;

        string host;

        public string html { get; private set; }
        public IHttpHelper _Http { get; private set; }
        public IMovieDb _Db { get; private set; }
        public SimpleSpider SetHttp(IHttpHelper h) {
            this._Http = h;
            Console.WriteLine($"_Http:{h}");
            return this;
        }
        public SimpleSpider SetDb(IMovieDb h)
        {
            this._Db = h;
            Console.WriteLine($"_Db:{h}");
            return this;
        }
        public void QuerySelector(List<string> codes)
        {
            if (string.IsNullOrEmpty(html))
            {
                Console.WriteLine("网页内容为空！");
            }
            else
            {
                if (codes.Count < 2)
                {
                    return;
                }
                var selectors = codes[1];
                using (IHtmlDocument dom = new HtmlParser().Parse(html))
                {
                    var data = dom.QuerySelector(selectors);
                    Console.WriteLine(data?.OuterHtml);
                }
            }

        }

        public void ScriptsSelectorAll(List<string> codes)
        {
            if (string.IsNullOrEmpty(html))
            {
                Console.WriteLine("网页内容为空！");
            }
            else
            {
                if (codes.Count < 2)
                {
                    return;
                }
                var selectors = codes[1];
                using (IHtmlDocument dom = new HtmlParser().Parse(html))
                {
                    var data = dom.Scripts.Where(m=>m.InnerHtml.Contains(selectors)).ToList();
                    Console.WriteLine($"查询结果{data?.Count ?? 0} 条符合条件");
                    if (data != null)
                    {
                        foreach (var d in data)
                        {
                            Console.WriteLine(d.InnerHtml);
                            var player_aaaa = d.InnerHtml.Replace("var player_aaaa=", "");
                            var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>(player_aaaa);
                        }
                        tempData = data.FirstOrDefault()?.InnerHtml;
                    }
                }
            }

        }
        /// <summary>
        /// 查询已有任务
        /// </summary>
        /// <param name="codes"></param>
        public void SelectorTask(List<string> codes)
        {
            if (_Db == null)
            {
                Console.WriteLine("数据库未设置！");
                return;
            }
            string name = "";
            if (codes.Count == 2)
            {
                name = codes[1].Trim();
            }
            var data = _Db.SelectTitle(name);
            Console.WriteLine($"查询到{data?.Count ?? 0}条数据！");
            data.ForEach(m =>
            {
                Console.WriteLine($"{m.Id}  | {m.Name} | {m.StartUrl} |");
            });

        }
        /// <summary>
        /// 查询已有任务明细
        /// </summary>
        /// <param name="codes"></param>
        public void SelectorTaskItem(List<string> codes)
        {
            if (_Db == null)
            {
                Console.WriteLine("数据库未设置！");
                return;
            }
            if (codes.Count < 2)
            {
                Console.WriteLine("参数有误！");
                return;
            }
            string id = codes[1].Trim();
            var data = _Db.SelectItems(id);
            Console.WriteLine($"查询到{data?.Count ?? 0}条数据！");
            data.ForEach(m =>
            {
                Console.WriteLine($"{m.Id}  | {m.Name} | {m.Url} |");
            });

        }
        /// <summary>
        /// 在线检索电影
        /// </summary>
        /// <param name="codes"></param>
        public void SeachMoive(List<string> codes)
        {
            if (_Db == null)
            {
                Console.WriteLine("数据库未设置！");
                return;
            }
            if (codes.Count < 2)
            {
                Console.WriteLine("参数有误！");
                return;
            }
            string name = codes[1].Trim();

            codes[0] = "to";
            codes[1] = string.Format(Kanjuji.SearchUrl,name);
            ToAsync(codes).Wait();

        }
        /// <summary>
        /// 播放
        /// </summary>
        /// <param name="codes"></param>
        public void PItem(List<string> codes)
        {
            if (_Db == null)
            {
                Console.WriteLine("数据库未设置！");
                return;
            }
            if (codes.Count < 2)
            {
                Console.WriteLine("参数有误！");
                return;
            }
            string id = codes[1].Trim();
            var data = _Db.SelectItem(id);
            if (data == null)
            {
                Console.WriteLine($"id无效！{id}");
                return;
            }
            // 在线播放
            bool o = codes.Count > 2;
            var url = o ? data.MUrl : $"{data.PId}_{data.PName}/{data.Name}/index.m3u8";
            System.Diagnostics.Process.Start(@"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe", $"http://localhost:8066?u={url}");

        }

        /// <summary>
        /// 开始一个任务
        /// </summary>
        /// <param name="codes"></param>
        public void RunTask(List<string> codes)
        {
            if (_Db == null)
            {
                Console.WriteLine("数据库未设置！");
                return;
            }
            string id = "";
            if (codes.Count == 2)
            {
                id = codes[1].Trim();
            }
            if (string.IsNullOrEmpty(id))
            {
                Console.WriteLine("id无效！");
                return;
            }
            var data = _Db.SelectTitleById(id);
            if (data == null || data.Count == 0) {
                Console.WriteLine($"id无效！{id}");
                return;
            }
            // 反射获取任务实例
            MovieSpiderBase.GetMovieSpiderBase(data[0].SType,data[0].StartUrl,data[0].Name,_Db,_Http).Start();

        }
        public void NewTask(List<string> codes)
        {
            if (_Db == null)
            {
                Console.WriteLine("数据库未设置！");
                return;
            }
            if (codes.Count < 4)
            {
                Console.WriteLine("参数有误！");
                return;
            }
            string name = codes[3];
            string url = codes[2];
            string fun = codes[1];

            MovieSpiderBase.GetMovieSpiderBase(fun,url, name, _Db, _Http).Start();

        }

        public void QuerySelectorAll(List<string> codes)
        {
            if (string.IsNullOrEmpty(html))
            {
                Console.WriteLine("网页内容为空！");
            }
            else
            {
                if (codes.Count < 2) {
                    return;
                }
                var selectors = codes[1];
                using (IHtmlDocument dom = new HtmlParser().Parse(html))
                {
                    var data = dom.QuerySelectorAll(selectors);
                    Console.WriteLine($"查询结果{data?.Length ?? 0} 条符合条件");
                    if (data != null) {
                        foreach (var d in data) {
                            Console.WriteLine(d.OuterHtml);
                        }
                    }
                }
            }

        }

        string getUrl(string url) {
            var _url = url;
            if (!_url.ToLower().StartsWith("http"))
                _url = this.host + url;
            Uri myUri = new Uri(_url);
            this.host = $"{myUri.Scheme}://{myUri.Host}";
            return _url;

        }
        /// <summary>
        /// 加载网页
        /// </summary>
        /// <param name="codes"></param>
        public async Task ToAsync(List<string> codes)
        {
            if (codes.Count >= 2)
            {
                var url = getUrl(codes[1]);
                if (_Http == null) _Http = new HttpHelper().SetLogger(_log);
                html = await _Http.GetHTMLByURLAsync(url);
                Console.WriteLine(html);
            }
            else {

                Console.WriteLine("输入有误，请输入：to 网址！");
            }
            
        }



    }
}
